package com.seguriapp.gwt.client.login;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.seguriapp.gwt.client.login.LoginPanelPresenter.Display;

public class LoginPanel extends Composite implements Display {

  private static LoginPanelUiBinder uiBinder = GWT.create(LoginPanelUiBinder.class);
  private static final String USERNAME_ERROR = "Ingresar usuario";
  private static final String PASSWORD_ERROR = "Ingresar contrase&ntilde;a";

  interface LoginPanelUiBinder extends UiBinder<Widget, LoginPanel> {
  }

  @UiField
  protected TextBox username;
  @UiField
  protected PasswordTextBox password;
  @UiField
  protected InlineLabel errorMessage;
  @UiField
  protected Anchor cancelarLink;
  @UiField(provided = true)
  protected FormPanel jForm;

  private LoginPanelPresenter presenter;

  public LoginPanel() {
    jForm = new FormPanel("_self");
    initWidget(uiBinder.createAndBindUi(this));
  }

  public void setPresenter(final LoginPanelPresenter presenter) {
    this.presenter = presenter;
  }

  @UiHandler("signinlink")
  protected void onSignInLinkClick(final ClickEvent event) {
    if (validateForm()) {
      presenter.validateCredentials(username.getText().trim(), password.getText().trim());
    }
  }

  private boolean validateForm() {
    showError("", false);
    if (username.getText() != null && username.getText().trim().length() == 0) {
      showError(USERNAME_ERROR, true);
      return false;
    }
    if (password.getText() != null && password.getText().trim().length() == 0) {
      showError(PASSWORD_ERROR, true);
      return false;
    }
    return true;
  }

  public void showError(final String errorMsg, final boolean showError) {
    errorMessage.setText(errorMsg);
    errorMessage.setVisible(showError);
  }

  public void setCloseHandler(final ClickHandler closeHanlder) {
    cancelarLink.addClickHandler(closeHanlder);
    cleanFields(true);
    showError("", false);
  }

  public void cleanFields(final boolean allFields) {
    if (allFields) {
      username.setText("");
    }
    password.setText("");
  }

  public void submitLoginForm() {
    jForm.submit();
  }

}
